from PetNetadmin.serializers import PetMessageSerializer
from admincharge.models import PetMessage
from utils.imageupload import ImageUpload
from utils.pagination import PetMessagePagination
from admincharge.utils.Authentication import MyTokenObtainPairSerializer
from admincharge.utils.jwt import MyJWTAuthentication
from rest_framework.permissions import IsAuthenticated
import os

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view


# 所有宠物基本信息
class PetNetMessageView(APIView):
    # 获取底下的所有数据 或者搜索框关键字返回
    authentication_classes = [MyJWTAuthentication]

    # permission_classes = [IsAuthenticated]
    def get(self, request):
        keyword = request.GET.get('keyword')
        # print(keyword)
        if keyword:
            pet_message_all_list = PetMessage.objects.filter(petname__contains=keyword)
        else:
            pet_message_all_list = PetMessage.objects.all()
        paginator = PetMessagePagination()
        result_page = paginator.paginate_queryset(pet_message_all_list, request)
        serializer = PetMessageSerializer(instance=result_page, many=True)
        result = {
            'data': serializer.data,
            'code': 2000,
            'msg': '获取成功'
        }
        return paginator.get_paginated_response(result)

    # 添加数据
    def post(self, request):
        get_message = request.data
        print(get_message)
        data = {
            'petname': get_message['pet_name'],
            'petsex': int(get_message['pet_sex']),
            'petage': float(get_message['pet_age']),
            'petkind': get_message['pet_kind'],
            'healthy': int(get_message['pet_healthy']),
            'imagesurl': get_message['fileList'],
            'petvaccines': int(get_message['pet_vaccines']),
            'petvaccinestime': get_message['pet_vaccinestime'],
            'apply_account':get_message['apply_account'],
            'description': get_message['description']
        }
        print(data)
        serializer = PetMessageSerializer(data=data, partial=True)
        if serializer.is_valid(raise_exception=True):
            print(serializer.validated_data)
            serializer.save()
            result = {
                'code': 2000,
                'msg': '上传保存成功'
            }
            return Response(status=status.HTTP_200_OK, data=result)


class UploadPetImageView(APIView):
    def post(self, request):
        result = ImageUpload(request, 'images')
        print(result)
        if result['code'] == 2000:
            return Response(data=result['img'])
        else:
            return Response('没有上传成功')


# 删除单个数据
@api_view(['POST'])
def deleteOnePetmsg(request, id):
    try:
        petMsg = PetMessage.objects.get(pk=id)
        imagefile = PetMessage.objects.get(pk=id).imagesurl
        print(imagefile)
        petMsg.delete()
        imagefile = imagefile.split(':8000/')[1]
        print(imagefile)
        if os.path.exists(imagefile):
            os.remove(imagefile)
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except PetMessage.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)


# 删除多个数据时
@api_view(['POST'])
def deleteManyPetmsg(request):
    try:
        ids = request.data['Ids']
        # 用来保存被删除对象的imgsurl字段
        # deleted_imgsurls = []
        for id in ids:
            pet_message = PetMessage.objects.get(id=id)
            imgsurl = pet_message.imagesurl
            imagefile = imgsurl.split(':8000/')[1]
            print(imagefile)
            if os.path.exists(imagefile):
                os.remove(imagefile)
            pet_message.delete()
        # print(deleted_imgsurls)
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except PetMessage.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)


@api_view(['POST'])
def editPetMsg(request):
    try:
        id = request.data['id']
        print(request.data)
        new_img_url = request.data['fileList']
        old_img_url = PetMessage.objects.get(id=id).imagesurl
        if new_img_url != old_img_url:
            print(old_img_url)
            old_img_url = old_img_url.split(':8000/')[1]
            if os.path.exists(old_img_url):
                os.remove(old_img_url)
                print(f'删除成功{old_img_url}')
        updateMsg = PetMessage.objects.get(id=id)
        data = {
            'petname': request.data['petname'],
            'petsex': int(request.data['petsex']),
            'petage': float(request.data['petage']),
            'petkind': request.data['petkind'],
            'healthy': int(request.data['healthy']),
            'imagesurl': request.data['fileList'],
            'petvaccines': int(request.data['petvaccines']),
            'petvaccinestime': request.data['petvaccinestime'],
            'apply_account': request.data['apply_account'],
            'description': request.data['description']
        }
        serializer = PetMessageSerializer(instance=updateMsg, data=data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
        result = {
            'code': 2000,
            'msg': '上传保存成功'
        }
        return Response(result)
    except PetMessage.DoesNotExist:
        return Response({"msg": '当前没有该记录可以修改'}, status=status.HTTP_404_NOT_FOUND)
